<?php
/**
 * Movie administration page
 *
 *
 * LICENSE: Some license information
 *
 * phpMMB version: 0.0.1
 *
 * $copyright  2007 SaWey
 * $license    GNU GPL v3.
 * $URL: http://www.sawey.be/phpMyMovieBox $
 * $Revision: 6 $
 * $LastChangedBy: sander.weyens $
 * $Date: 2008-01-14 22:20:38 +0000 (Mon, 14 Jan 2008) $
*/

//print submenu
$tpl->define_dynamic('mymovies_submenu', 'menu');
$tpl->parse('SUBMENU',".mymovies_submenu");

//load template
$tpl->define( 
		array( 
				'mymovies'   	=> "admin_mymovies.htm",
				'common'	   	=> "admin_common.htm",
		)
	);

switch($function)
{
	case 'add_movie_lookup':
		
		include('includes/lib_imdb.php');
		$imdb = new IMDB();
			
		//see if the search has been made
		if(isset($_POST['Submit']))
		{
			//search imdb site for titles
			$search_results = $imdb->searchTitles($_POST['movie_title']);
			
			if($search_results)
			{
				//we have some matches, print it out
				$tpl->define_dynamic('imdb_results', 'mymovies');
				$tpl->define_dynamic('imdb_results_row', 'mymovies');
				$class = 'row_1';
				foreach($search_results as $imdb_movie)
				{	
					$class = ($class == 'row_1') ? 'row_2' : 'row_1';
					$tpl->assign(
							array(
								'RES_TITLE'		=> shorten_string($imdb_movie['2']) . ' ' . $imdb_movie['3'],
								'RES_ID'		=> $imdb_movie['1'],
								'ALTERNATE_COLORS_CLASS' => $class,
							)
						);
					$tpl->parse('IMDB_RESULTS_ROW', '.imdb_results_row');
				}
				$tpl->parse('BODY', '.imdb_results');
			}
			else
			{
				//no matches found
			}
		}
		else if(isset($_GET['add']))
		{
			//get imdb movie info
			$imdb_url = 'http://www.imdb.com/title/' . $_GET['add'] . '/';
			
			//what to do with the image
			$imdb->save_image = ($config['save_image'] == 1) ? true : false;
			
			if(!$imdb->getMovieInfo($imdb_url))
			{
				//we could not get the imdb page
				$back = sprintf($lang['LANG_CLICK_TRY_AGAIN'], ' <a href="javascript:void(0)" onClick="window.location.reload()">' . $lang['LANG_HERE'] . '</a>');
				$msg = $lang['LANG_IMDB_ERROR'] . '<br />' . $back;
				print_short_message($msg);
				break;
			}
			
			$tpl->define_dynamic('add_movie_form', 'mymovies');
			
			$poster = $imdb->getPoster();
			//print the add_movie field with imdb result filled in
			$tpl->assign(
							array(
								'RES_POSTER'	=> $poster['url'],
								'POSTER'		=> $poster['html'],
								'RES_TITLE'		=> $imdb->name,
								'RES_AKA'		=> $imdb->aka,
								'RES_DIRECTOR' 	=> $imdb->director,
								'RES_YEAR'		=> $imdb->year,
								'RES_WRITER'	=> $imdb->writer,
								'RES_TAGLINE'	=> $imdb->tagline,
								'RES_PLOT'		=> $imdb->plot,
								'RES_COUNTRY'	=> $imdb->country,
								'RES_LANGUAGE'	=> $imdb->language,
								'RES_COLOR'		=> $imdb->color,
								'RES_IMDB_RATING'=> $imdb->stars,
								'RES_AWARDS'	=> $imdb->awards,
								'RES_IMDB_ID'	=> $imdb->id,
								'SUBMIT' 		=> $lang['LANG_ADD_MOVIE'],
								'FUNCTION'		=> 'add_movie',
							)
						);
						
			$tpl->define_dynamic('add_movie_form_genre', 'mymovies');
			//translate the genres and put them in an array
			$genres = explode("/", $imdb->genre);
			
			$genre_counter = 0;
			$genre_total = count($genres) - 1;
			if(is_array($genres))
			{
				foreach($genres as $genre)
				{
					$tpl->assign(array('RES_GENRE' => $lang_genre[trim($genre)]));
					if($genre_counter != $genre_total)
					{
						$tpl->parse('ADD_MOVIE_FORM_GENRE', '.add_movie_form_genre');
						$genre_counter ++;
					}
				}
			}
			
			
			$tpl->define_dynamic('add_movie_form_cast', 'mymovies');
			//add cast to form
			//first we need to take the first person of the list
			$tmp = $imdb->cast;
			$first_person = $tmp[0];
			unset($tmp[0]);
			$imdb->cast = $tmp;
			if(is_array($imdb->cast))
			{
				foreach($imdb->cast as $person)
				{
					$tpl->assign(array('RES_CAST_NAME' 	 => $person['name']));
					$tpl->assign(array('RES_CAST_AS' => $person['character']));
					$tpl->parse('ADD_MOVIE_FORM_CAST', '.add_movie_form_cast');
				}
			}
			//assign the first one now
			$tpl->assign(array('RES_CAST_NAME' 	 => $first_person['name']));
			$tpl->assign(array('RES_CAST_AS' => $first_person['character']));
			
			$tpl->parse('BODY',".add_movie_form");
			
		}
		else
		{
			$tpl->define_dynamic('imdb_search', 'mymovies');
			$tpl->parse('BODY',".imdb_search");
		}
		break;
	
	
	case 'add_movie_manual':
	
		$tpl->define_dynamic('add_movie_form', 'mymovies');
		$tpl->define_dynamic('add_movie_form_genre', 'mymovies');
		$tpl->assign(array(
						'SUBMIT' 	=> $lang['LANG_ADD_MOVIE'],
						'FUNCTION'	=> 'add_movie',
					));
		for($i = 1; $i < $config['number_genres']; $i++)
		{
			$tpl->parse('ADD_MOVIE_FORM_GENRE', '.add_movie_form_genre');
		}
		$tpl->define_dynamic('add_movie_form_cast', 'mymovies');
		for($i = 1; $i < $config['number_cast']; $i++)
		{
			$tpl->parse('ADD_MOVIE_FORM_CAST', '.add_movie_form_cast');
		}
		$tpl->parse('BODY',".add_movie_form");		
		break;
	
	
	case 'add_movie':
		
		//clear empty fields and make db safe
		$clean_post = clean_array($_POST);
		
		//first we need to check if this movie isn't already in the db 
		if(!isset($_POST['ignore_and_add']))
		{
			$clean_post = $_POST;

			$sql = 'SELECT movie_id FROM ' . $db_prefix . 'movies WHERE title = "' . $clean_post['movie_title'] . '" AND year = "' . $clean_post['movie_year'] . '"';
			if($db->get_var($sql) != null)
			{
				//movie already exists in db, ask for permission to proceed
				$tpl->define_dynamic('movie_exists', 'common');
				$tpl->define_dynamic('movie_exists_hidden', 'common');
				$msg = sprintf($lang['LANG_MOVIE_EXISTS'], stripslashes($clean_post['movie_title']), $clean_post['movie_year']);
				$tpl->assign(array('MOVIE_EXISTS' => $msg));
				
				foreach($clean_post as $name => $value){
					if(is_array($value))
					{
						foreach($value as $value_name => $value_value)
						{
							$tpl->assign(array(
										'HIDDEN_NAME' => $name . '[]',
										'HIDDEN_VAL' => stripslashes(htmlentities($value_value)),
									));
							$tpl->parse('MOVIE_EXISTS_HIDDEN', '.movie_exists_hidden');
						}
					}
					else
					{
						$tpl->assign(array(
									'HIDDEN_NAME' => $name,
									'HIDDEN_VAL' => stripslashes(htmlentities($value)),
								));
						$tpl->parse('MOVIE_EXISTS_HIDDEN', '.movie_exists_hidden');
					}
				}
				$tpl->parse('BODY', '.movie_exists');

				break;
			}
		}
		
		//add the movie to the db
		//first we insert the country, so we can use it in the movies table
		if(isset($clean_post['movie_country']))
		{
			$sql_country = 'SELECT country_id FROM ' . $db_prefix . 'countries WHERE country="' . $clean_post['movie_country'] . '"';
			if(($country_id = $db->get_var($sql_country)) == null)
			{
				//country is not available, insert it and get its id
				$sql = 'INSERT INTO ' . $db_prefix . 'countries (country) VALUES("' . $clean_post['movie_country'] . '")';
				$db->query($sql);
				$country_id = $db->insert_id;
			}
		}
		
		$sql = 'INSERT INTO ' . $db_prefix . 'movies (title, aka, year, tagline, plot, country, color, imdb_rating, personal_rating, poster, imdb_id) VALUES('
			 . '"' . $clean_post['movie_title'] . '", "' . $clean_post['movie_aka'] . '", "' . $clean_post['movie_year'] . '", "' . $clean_post['movie_tagline'] . '", "'
			 . $clean_post['movie_plot'] . '", ' . $country_id . ', "' . $clean_post['movie_color'] . '", "' . $clean_post['movie_imdb_rating'] . '", "'
			 . $db->escape($clean_post['movie_personal_rating']) . '", "' . $clean_post['movie_poster'] . '", "' . $clean_post['movie_imdb_id'] . '")';
		$db->query($sql);
		$movie_id = $db->insert_id;
		
		//insert people
		if(isset($clean_post['movie_director']))
		{
			insert_people($clean_post['movie_director'], $movie_id, 'd');
		}
		if(isset($clean_post['movie_director']))
		{
			insert_people($clean_post['movie_cast_name'], $movie_id, 'a', $clean_post['movie_cast_as']);
		}
		if(isset($clean_post['movie_writer']))
		{
			insert_people($clean_post['movie_writer'], $movie_id, 'w');
		}
		
		//insert the genre(s)
		insert_movie_item($movie_id, $clean_post['movie_genres'], 'genre', 'genres');
		
		//insert the award(s)
		insert_movie_item($movie_id, $clean_post['movie_awards'], 'award', 'awards');
		
		//insert the language(s)
		insert_movie_item($movie_id, $clean_post['movie_language'], 'language', 'languages');
		
		//print page telling movie was added
		$back = sprintf($lang['LANG_CLICK_GO_BACK'], ' <a href="?page=admin&sub=mymovies">' . $lang['LANG_HERE'] . '</a>');
		$msg = stripslashes($clean_post['movie_title']) . ' ' . $lang['LANG_ADD_SUCCESS'] . '<br />' . $back;
		print_short_message($msg);
		
		break;
	
	
	case 'remove':
	
		//remove this movie
		$movie_id = $_GET['m'];
		foreach($movie_dependent_table as $tablename)
		{
			$sql = 'DELETE FROM ' . $db_prefix . $tablename . ' WHERE movie_id = ' . $movie_id;
			$db->query($sql);
		}
		
		//print page telling movie was removed
		$back = sprintf($lang['LANG_CLICK_GO_BACK'], ' <a href="?page=admin&sub=mymovies">' . $lang['LANG_HERE'] . '</a>');
		$msg = $lang['LANG_REMOVE_SUCCES'] . '<br />' . $back;
		print_short_message($msg);
		
		break;
	
	
	case 'edit':
	
		//edit this movie
		$movie_id = $_GET['m'];
		$movie = get_movie_info($movie_id);
		
		$tpl->define_dynamic('add_movie_form', 'mymovies');
		
		//here comes the hard work -> parse movie in the template
		$poster = '<img id="poster_image" src="' . $movie['main']['poster'] . '" alt="' . $movie['main']['title'] . '"/>';
		$tpl->assign(array(
						'RES_POSTER'	=> $movie['main']['poster'],
						'POSTER'		=> $poster,
						'RES_TITLE'		=> $movie['main']['title'],
						'RES_MOVIE_ID'	=> $movie['main']['movie_id'],
						'RES_AKA'		=> $movie['main']['aka'],
						'RES_YEAR'		=> $movie['main']['year'],
						'RES_TAGLINE'	=> $movie['main']['tagline'],
						'RES_PLOT'		=> $movie['main']['plot'],
						'RES_COUNTRY'	=> $movie['main']['country'],
						'RES_COLOR'		=> $movie['main']['color'],
						'RES_IMDB_RATING'=> $movie['main']['imdb_rating'],
						'RES_PERSONAL_RATING'=> $movie['main']['personal_rating'],
						'RES_IMDB_ID'	=> $movie['main']['imdb_id'],
						'SUBMIT'		=> $lang['LANG_SAVE'],
						'FUNCTION'		=> 'save',
					));
		
		//parse directors
		$tpl_tags = array(
			'RES_DIRECTOR'	=> 'name'
		);
		parse_movie_item_on_template($movie['people']['d'], 'add_movie_form_director', $tpl_tags);
		
		//parse genres
		$tpl_tags = array(
			'RES_GENRE'	=> 'numeric'
		);
		parse_movie_item_on_template($movie['genres'], 'add_movie_form_genre', $tpl_tags);
		
		//parse cast
		$tpl_tags = array(
			'RES_CAST_NAME'	=> 'name',
			'RES_CAST_AS'	=> 'character',
		);
		parse_movie_item_on_template($movie['people']['a'], 'add_movie_form_cast', $tpl_tags);
		
		//parse writers
		$tpl_tags = array(
			'RES_WRITER'	=> 'name'
		);
		parse_movie_item_on_template($movie['people']['w'], 'add_movie_form_writer', $tpl_tags);
		
		//parse languages
		$tpl_tags = array(
			'RES_LANGUAGE'	=> 'numeric'
		);
		parse_movie_item_on_template($movie['languages'], 'add_movie_form_language', $tpl_tags);
		
		//parse genres
		$tpl_tags = array(
			'RES_AWARDS'	=> 'numeric'
		);
		parse_movie_item_on_template($movie['awards'], 'add_movie_form_awards', $tpl_tags);		

		$tpl->parse('BODY',".add_movie_form");
		
		break;
		
		
	case 'save':
	
		//save the edited movie
		$movie_id = $_POST['movie_id'];
		$clean_post = clean_array($_POST);
		//first we delete all things about this movie
		unset($movie_dependent_table[0]);
		foreach($movie_dependent_table as $tablename)
		{
			$sql = 'DELETE FROM ' . $db_prefix . $tablename . ' WHERE movie_id = ' . $movie_id;
			$db->query($sql);
		}
		
		//then we insert the country, so we can use it in the movies table
		if(isset($clean_post['movie_country']))
		{
			$sql_country = 'SELECT country_id FROM ' . $db_prefix . 'countries WHERE country="' . $clean_post['movie_country'] . '"';
			if(($country_id = $db->get_var($sql_country)) == null)
			{
				//country is not available, insert it and get its id
				$sql = 'INSERT INTO ' . $db_prefix . 'countries (country) VALUES("' . $clean_post['movie_country'] . '")';
				$db->query($sql);
				$country_id = $db->insert_id;
			}
		}
		
		//now we update the movies table
		$sql = 'UPDATE ' . $db_prefix . 'movies SET'
			 . ' title = "' . $clean_post['movie_title'] . '",' 
			 . ' aka = "' . $clean_post['movie_aka'] . '",' 
			 . ' year = "' . $clean_post['movie_year'] . '",' 
			 . ' tagline = "' . $clean_post['movie_tagline'] . '",' 
			 . ' plot = "' . $clean_post['movie_plot'] . '",' 
			 . ' country = ' . $country_id . ',' 
			 . ' color = "' . $clean_post['movie_color'] . '",' 
			 . ' imdb_rating = "' . $clean_post['movie_imdb_rating'] . '",' 
			 . ' personal_rating = "' . $db->escape($clean_post['movie_personal_rating']) . '",' 
			 . ' poster = "' . $clean_post['movie_poster'] . '",' 
			 . ' imdb_id = "' . $clean_post['movie_imdb_id'] . '"'
			 . ' WHERE movie_id = ' . $movie_id;
		$db->query($sql);
		
		//insert the directors
		if(isset($clean_post['movie_director']))
		{
			insert_people($clean_post['movie_director'], $movie_id, 'd');
		}
		
		//insert the actors
		if(isset($clean_post['movie_cast_name']))
		{
			insert_people($clean_post['movie_cast_name'], $movie_id, 'a', $clean_post['movie_cast_as']);
		}
		
		//insert the writers
		if(isset($clean_post['movie_writer']))
		{
			insert_people($clean_post['movie_writer'], $movie_id, 'w');
		}
		
		//insert the genres
		insert_movie_item($movie_id, $clean_post['movie_genre'], 'genre', 'genres');
		
		//insert the awards
		insert_movie_item($movie_id, $clean_post['movie_awards'], 'award', 'awards');
		
		//insert the language
		insert_movie_item($movie_id, $clean_post['movie_language'], 'language', 'languages');
		
		//print page telling movie was added
		$back = sprintf($lang['LANG_CLICK_GO_BACK'], ' <a href="?page=admin&sub=mymovies">' . $lang['LANG_HERE'] . '</a>');
		$msg = stripslashes($clean_post['movie_title']) . ' ' . $lang['LANG_MOVIE_SAVED'] . '<br />' . $back;
		print_short_message($msg);
		
		break;
		
		
	default:
	
		//show list of movies with edit/remove links
		$tpl->define_dynamic('movie_list', 'mymovies');
		$tpl->define_dynamic('movie_list_row', 'mymovies');
		
		$link = '?page=admin&sub=mymovies';
		
		//create sort order
		if($_GET['ascdsc'] == 'd') 
		{
			$ascdsc = ' DESC';
			$link .= '&ascdsc=d';
		}
		else
		{
			$ascdsc = ' ASC';
		}
		
		if(!isset($_GET['o']) && in_array($config['show_movies_order'], $sort_orders['movies']))
		{
			$order = ' ORDER BY ' . $config['show_movies_order'];
		}
		else if(isset($_GET['o']) && in_array($_GET['o'], $sort_orders['movies']))
		{
			$order = ' ORDER BY ' . $_GET['o'];
			$link .= '&o=' . $_GET['o'];
		}
		else
		{
			$order = ' ORDER BY movie_id';
		}
		$order .= $ascdsc;
		
		//if we have a limit, create the paging
		$limit = '';
		$sql = 'SELECT COUNT(movie_id) FROM ' . $db_prefix . 'movies ';
		$total = $db->get_var($sql);
		$current_page = (isset($_GET['p']) && $_GET['p'] != '') ? $_GET['p'] : 0;
		if($total > $config['show_movies_per_page'])
		{
			//we can't show them on 1 page, create paging
			$paging = create_paging($total, $link, $current_page);
			$limit = ' LIMIT ' . $paging['limit']['start'] . ', ' . $paging['limit']['stop'];
			$tpl->assign('PAGING', $paging['nav']);
		}

		
		//select movies from db
		$sql = 'SELECT movie_id, title FROM ' . $db_prefix . 'movies' . $order . $limit;
		$movies = $db->get_results($sql, ARRAY_A);
		
		$class == 'row_1';
		if(is_array($movies))
		{
			foreach($movies as $movie)
			{
				$class = ($class == 'row_1') ? 'row_2' : 'row_1';
				$tpl->assign(array(
								'ALTERNATE_COLORS_CLASS' 	 => $class,
								'MOVIE_ID'				 	 => $movie['movie_id'],
								'MOVIE_TITLE'			 	 => shorten_string($movie['title']),
							));
				
				$tpl->parse('MOVIE_LIST_ROW', '.movie_list_row');
			}
		}
		else
		{
			print_short_message($lang['LANG_NO_MOVIES']);
		}

		$tpl->parse('BODY', '.movie_list');
		break;
}

function parse_movie_item_on_template($movie_item, $tpl_item, $tpl_tags, $tpl_parent = 'mymovies')
{
	global $tpl;
	if(is_array($movie_item))
	{
		$tpl->define_dynamic($tpl_item, $tpl_parent);
		//get the first one, as we have to parse it at the end
		$first_one = $movie_item[0];
		unset($movie_item[0]);
		foreach($movie_item as $parsable)
		{
			$assign_arr = '';
			foreach($tpl_tags as $tag => $movie_item_key)
			{
				if($movie_item_key == 'numeric')
				{
					$assign_arr[$tag] = $parsable;
				}
				else
				{
					$assign_arr[$tag] = $parsable[$movie_item_key];
				}
			}
			
			$tpl->assign($assign_arr);
			$tpl->parse(strtoupper($tpl_item), '.' . $tpl_item);
		}
		
		//assign first_one to the template
		$assign_arr = '';
		foreach($tpl_tags as $tag => $movie_item_key)
		{
			if($movie_item_key == 'numeric')
			{
				$assign_arr[$tag] = $first_one;
			}
			else
			{
				$assign_arr[$tag] = $first_one[$movie_item_key];
			}
		}
		$tpl->assign($assign_arr);
	}
}

function insert_people($people_arr, $movie_id, $role, $cast_as_array = '')
{
	global $db, $db_prefix;
	foreach($people_arr as $key => $someone)
	{
		$sql = 'SELECT people_id FROM ' . $db_prefix . 'people WHERE name = "' . $someone . '"';
		if(($people_id = $db->get_var($sql)) == null)
		{
			//this someone is not available, insert it
			$sql = 'INSERT INTO ' . $db_prefix . 'people (name) VALUES("' . $someone . '")';
			$db->query($sql);
			$people_id = $db->insert_id;
		}
		//add this someone to this movie, if it is an actor, also add character
		if($role != 'a')
		{
			$sql = 'INSERT INTO ' . $db_prefix . 'movies_people (movie_id, people_id, role) VALUES(' . $movie_id . ', ' . $people_id . ', "' . $role . '")';
			$db->query($sql);
		}
		else
		{
			$character_id = insert_character($cast_as_array[$key]);
			$sql = 'INSERT INTO ' . $db_prefix . 'movies_people (movie_id, people_id, role, character_id) VALUES(' . $movie_id . ', ' . $people_id . ', "a", ' . $character_id . ')';
			$db->query($sql);
		}
	}
}

function insert_character($character)
{
	global $db, $db_prefix;
	//see if we already have this one
	$sql = 'SELECT character_id FROM ' . $db_prefix . 'characters WHERE name = "' . $character . '"';
	if(($character_id = $db->get_var($sql)) == null)
	{
		//this character is not available, insert it
		$sql = 'INSERT INTO ' . $db_prefix . 'characters (name) VALUES("' . $character . '")';
		$db->query($sql);
		$character_id = $db->insert_id;
	}
	return $character_id;
}

function insert_movie_item($movie_id, $item_arr, $item_name, $item_name_plural)
{
	global $db, $db_prefix;
	if(is_array($item_arr))
	{
		foreach($item_arr as $item)
		{
			$sql = 'SELECT ' . $item_name . '_id FROM ' . $db_prefix . $item_name_plural . ' WHERE ' . $item_name . ' = "' . $item . '"';
			if(($item_id = $db->get_var($sql)) == null)
			{
				//item doesn't exist, create it
				$sql = 'INSERT INTO ' . $db_prefix . $item_name_plural . ' (' . $item_name . ') VALUES("' . $item . '")';
				$db->query($sql);
				$item_id = $db->insert_id;
			}
			//add item to movie
			$sql = 'INSERT INTO ' . $db_prefix . 'movies_' . $item_name_plural . ' (movie_id, ' . $item_name . '_id) VALUES(' . $movie_id . ', ' . $item_id . ')';
			$db->query($sql);
		}
	}	
}
	
function clean_array($array)
{
	global $db;
	foreach($array as $key => $value)
	{
		if(is_array($value))
		{
			$array[$key] = clean_array($value);
		}
		else if(trim($value) == '')
		{
			unset($array[$key]);
		}
		else
		{
			$array[$key] = $db->escape($value);
		}
	}
	return $array;
}

function print_short_message($message)
{
	global $tpl;
	$tpl->define_dynamic('short_message', 'common');
	$tpl->assign(array('MESSAGE' => $message));
	$tpl->parse('BODY', '.short_message');
}
?>